package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.mapper.LessonMapper;
import com.fjh.springboot_01.pojo.lesson.Lesson;
import com.fjh.springboot_01.pojo.lesson.PageBean;
import com.fjh.springboot_01.service.LessonService;
import com.fjh.springboot_01.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class LessonServiceImpl implements LessonService {
    @Autowired
    private LessonMapper lessonMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Lesson lesson) {
        try {
            // 设置创建时间和更新时间
            lesson.setCreateTime(LocalDateTime.now());
            lesson.setUpdateTime(LocalDateTime.now());

            // 获取当前用户ID
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            if (userId == null) {
                throw new RuntimeException("用户未登录");
            }
            lesson.setCreateUser(userId);

            // 保存课程信息
            lessonMapper.add(lesson);
            
            System.out.println("课程添加成功，ID: " + lesson.getId());
        } catch (Exception e) {
            System.err.println("课程添加失败：" + e.getMessage());
            throw new RuntimeException("课程添加失败：" + e.getMessage());
        }
    }

    @Override
    public PageBean<Lesson> list(Integer pageNum, Integer pageSize, Integer categoryId, String keyword, Integer userId) {
        // 创建 PageBean 对象
        PageBean<Lesson> pb = new PageBean<>();

        // 参数验证和默认值设置
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 计算起始索引
        int start = (pageNum - 1) * pageSize;

        // 打印分页参数
        System.out.println("分页参数 - pageNum: " + pageNum + ", pageSize: " + pageSize + ", start: " + start);
        System.out.println("查询参数 - categoryId: " + categoryId + ", keyword: " + keyword + ", userId: " + userId);

        try {
            // 查询总记录数
            Integer count = lessonMapper.count(userId, categoryId, keyword);
            System.out.println("总记录数: " + count);

            if (count > 0) {
                // 查询当前页数据
                List<Lesson> lessons = lessonMapper.list(userId, categoryId, keyword, start, pageSize);
                System.out.println("当前页数据条数: " + (lessons != null ? lessons.size() : 0));
                
                // 填充到 PageBean
                pb.setTotal(count.longValue());
                pb.setItems(lessons);
            } else {
                pb.setTotal(0L);
                pb.setItems(List.of());
            }
        } catch (Exception e) {
            System.err.println("查询课程列表失败：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("查询课程列表失败：" + e.getMessage());
        }

        return pb;
    }

    @Override
    public void deleteById(Integer id) {
        // 获取当前用户ID和角色
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer currentUserId = (Integer) map.get("id");
        Integer userRole = (Integer) map.get("role");
        
        if (currentUserId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 获取课程创建者ID
        Integer creatorId = lessonMapper.getLessonCreator(id);
        if (creatorId == null) {
            throw new RuntimeException("课程不存在");
        }

        // 管理员可以删除任何课程
        boolean isAdmin = userRole != null && userRole == 2;
        
        // 检查是否为课程创建者或管理员
        if (!isAdmin && !currentUserId.equals(creatorId)) {
            throw new RuntimeException("无权删除他人的课程");
        }

        lessonMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Lesson lesson) {
        try {
            // 获取当前用户ID和角色
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer currentUserId = (Integer) map.get("id");
            Integer userRole = (Integer) map.get("role");
            
            if (currentUserId == null) {
                throw new RuntimeException("用户未登录");
            }

            // 获取课程创建者ID
            Integer creatorId = lessonMapper.getLessonCreator(lesson.getId());
            if (creatorId == null) {
                throw new RuntimeException("课程不存在");
            }

            // 管理员可以修改任何课程
            boolean isAdmin = userRole != null && userRole == 2;
            
            // 检查是否为课程创建者或管理员
            if (!isAdmin && !currentUserId.equals(creatorId)) {
                throw new RuntimeException("无权修改他人的课程");
            }

            // 设置更新时间
            lesson.setUpdateTime(LocalDateTime.now());
            
            // 打印更新信息
            System.out.println("正在更新课程，ID: " + lesson.getId());
            System.out.println("更新用户ID: " + currentUserId);
            System.out.println("更新用户角色: " + userRole);
            System.out.println("课程创建者ID: " + creatorId);
            
            lessonMapper.update(lesson);
            System.out.println("课程更新成功");
        } catch (Exception e) {
            System.err.println("课程更新失败：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("课程更新失败：" + e.getMessage());
        }
    }

    @Override
    public Lesson getLessonById(Integer id) {
        try {
            // 调用mapper方法获取课程
            return lessonMapper.getById(id);
        } catch (Exception e) {
            System.err.println("获取课程失败：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
